﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public interface IServer
    {
        Task StartAsync(RequestDelegate handler);
    }

    public class HttpListenerServer : IServer
    {
        HttpListener _httpListener;
        string[] _urls;
        public HttpListenerServer(params string[] urls)
        {
            _httpListener = new HttpListener();
            _urls = urls.Any() ? urls : new string[] { "http://localhost:5000" };
        }

        public async Task StartAsync(RequestDelegate handler)
        {
            Array.ForEach(_urls, url => _httpListener.Prefixes.Add(url));

            _httpListener.Start();

            while (true)
            {
                var context = await _httpListener.GetContextAsync();
                var httpContet = new HttpContext();
                httpContet.Request = new HttpRequest() { Body = context.Request.InputStream };
                httpContet.Response = new HttpResponse() { Body = context.Response.OutputStream };
                await handler(httpContet);
                context.Response.Close();
            }
        }
    }
}
